#include "avataritem.h"

AvatarItem::AvatarItem(const QIcon &avatar, const QString &name)
{
    this->setFixedSize(35,60);

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setContentsMargins(0,0,0,0);
    layout->setSpacing(0);
    this->setLayout(layout);

    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(35,35);
    avatarBtn->setIconSize(QSize(35,35));
    avatarBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    avatarBtn->setStyleSheet("QPushButton {border: 1px solid rgb(218, 218, 218);}");
    avatarBtn->setIcon(avatar);

    nameLabel = new QLabel();
    QFont font;
    font.setFamily("微软雅黑");
    font.setPixelSize(12);
    nameLabel->setFont(font);
    nameLabel->setAlignment(Qt::AlignCenter);

    //截断名称逻辑
    QFontMetrics metrics(font);
    int originalWidth = metrics.horizontalAdvance(name);
    const int MAX_WIDTH = 50;
    //超过则进行截断处理
    if(originalWidth > MAX_WIDTH)
    {
        //截断分隔符
        QString ellipsis = "...";

        int ellipsisWidth = metrics.horizontalAdvance(ellipsis);
        int availableWidth = MAX_WIDTH - ellipsisWidth;
        // 取左侧 n 个字符
        QString truncatedName = name.left(name.length() * availableWidth / originalWidth);
        nameLabel->setText(truncatedName + ellipsis);
    }
    else
        nameLabel->setText(name);

    //添加到布局管理器中
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);
}
